from datetime import datetime, date, timedelta

from django.conf import settings

from finance.util.paging import PagedQuery, PageLinks

import logging

import pytz
from pytz import timezone

def utc_from_localtime(datetime):
    if datetime.tzinfo is None:
        from_tz = pytz.timezone(settings.USER_TIME_ZONE)
        datetime = datetime.replace(tzinfo=from_tz).astimezone(pytz.utc)
    else:
        datetime = datetime.astimezone(pytz.utc)
    return datetime

def localtime_from_utc(datetime):
    from_tz = pytz.timezone(settings.USER_TIME_ZONE)
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=pytz.utc).astimezone(from_tz)
    else:
        datetime = datetime.astimezone(from_tz)
    return datetime

class JSONMsg(dict):
    def set_value(self, key, value):
        self.setdefault(key, value)
    def get_value(self, key):
        return self.get(key, "")
    def create(self, status, msg):
        self['status'] = status
        self['msg'] = msg
    def success(self, msg):
        self['status'] = 'success'
        self['msg'] = msg
    def failure(self, msg):
        self['status'] = 'failure'
        self['msg'] = msg

def paginate(req, query):
    args = req.GET.copy()
    cur_page = int(args.get('page', 1))
    pq = PagedQuery(query, settings.NUMBER_OF_ITEMS_IN_PAGE)
    entities = pq.fetch_page(cur_page)
    num_pages = pq.page_count()
    pagelinks = PageLinks(cur_page, num_pages, req.path, 'page')

    return {
            'cur_page': cur_page,
            'num_pages': num_pages,
            'entities': entities,
            'pagelinks': pagelinks.get_links(),
            'args': args.urlencode(),
            }

def get_this_year():
    return datetime.now().year

def get_this_month():
    return datetime.now().month

def get_today():
    return  date.today()

def shorten_name(name):
    return filter((lambda x: ord(x)<91 and ord(x)>64), name)

def get_date(dt, years=0, months=0, days=0):
    ndt = dt + timedelta(days=days)
    m = (ndt.month + months)%12
    y = ndt.year + years + (ndt.month + months)/12
    return date(y, m, ndt.day)